package it.cums.controller;

import it.cums.model.Country;
import it.cums.model.Customers;
import it.cums.model.Products;
import it.cums.model.Suppliers;
import it.cums.util.CountryManager;
import it.cums.util.HibernateUtil;
import it.cums.util.MessageCreator;

import java.util.List;

public class ApplicationController {
	private Customers customers;
	private Products products;
	private Suppliers suppliers;
	private List<Country> countries;
	private static ApplicationController appController;
	
	private ApplicationController() {
		boolean successful = false;
		try {
			HibernateUtil.testConnection();
			successful = true;
		} catch (ExceptionInInitializerError e1) {
			MessageCreator.showErrorMessage(e1.getCause().getMessage());
		} catch (Exception e2) {
			MessageCreator.showErrorMessage(e2.getCause().getMessage());
		}
		customers = new Customers();
		products = new Products();
		suppliers = new Suppliers();
		countries = CountryManager.getInstance().listCountries();
		if (successful && countries.size() == 0) {
			CountryManager.getInstance().initializeCountries();
			countries = CountryManager.getInstance().listCountries();
		}
	}
	
	public static ApplicationController getInstance() {
		if (appController == null) {
			appController = new ApplicationController();
		}
		return appController;
	}
	
	public Customers getCustomers() {
		return customers;
	}
	
	public Products getProducts() {
		return products;
	}
	
	public Suppliers getSuppliers() {
		return suppliers;
	}
	
	public List<Country> getCountries() {
		return countries;
	}
	
	public Country getCountry(String description) {
		if (!description.equals("")) {
			for (Country country : appController.getCountries()) {
				if (country.getDescription().equals(description)) {
					return country;
				}
			}	
		}
		return null;
	}
}